import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home',
    component: () => import('@/views/layout'),
    children: [
      {
        path: 'home',
        component: () => import('@/views/home')
      },
    ]
  },
  {
    path: '/shop',
    redirect: '/shop/category-list',
    component: () => import('@/views/layout'),
    children: [
      {
        path: 'category-list',
        component: () => import('@/views/shop/category-list')
      },
      {
        path: 'shop-list',
        component: () => import('@/views/shop/shop-list')
      },
      {
        path: 'shop-add',
        component: () => import('@/views/shop/shop-add')
      },
      {
        path: 'shop-edit',
        component: () => import('@/views/shop/shop-edit')
      },
      {
        path: 'brand',
        component: () => import('@/views/shop/brand')
      },
      {
        path: 'brand-edit',
        component: () => import('@/views/shop/brand-edit')
      },
      {
        path: 'sale',
        component: () => import('@/views/shop/sale')
      },
      {
        path: 'unit',
        component: () => import('@/views/shop/unit')
      },
      {
        path: 'freight',
        component: () => import('@/views/shop/freight')
      },
      {
        path: 'gradient-price',
        component: () => import('@/views/shop/gradient-price')
      },
      {
        path: 'gradient-edit',
        component: () => import('@/views/shop/gradient-edit')
      },
      {
        path: 'freight-edit',
        component: () => import('@/views/shop/freight-edit')
      },
      {
        path: 'category-edit',
        component: () => import('@/views/shop/category-edit')
      },
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login/index'),
  },
]

const router = new VueRouter({
  routes
})
const whiteList = ['/login', '/reg'] // 白名单：无需登录就能访问的路由地址
// 全局前置路由守卫
// 浏览器第一次打开项目页面 会触发一次全局前置路由守卫
// 有token就证明登录了 无token未登录
// next()如果强制切换路由地址 会再次走路由守卫 会再次去匹配路由表
router.beforeEach((to, from, next) => {
  const token=localStorage.getItem('token')
  if (token) {
    // 登录了
    if (to.path === '/login'){
      next('/')
    }else {
      next()
    }

  } else {
    // 未登录
    // includes 数组方法  作用：判断值是否在数组里面出现过  出现过就返回ture
    if (whiteList.includes(to.path)) {
      // 未登录 可以访问的路由地址 则放行(路由全局守卫不会再次触发了 而是匹配路由表 让组件挂载)
      next()
    } else {
      // next()强制跳转到登录页
      next('/login')
    }
  }
})
export default router
